package com.shardings.sharding.shardingAlgorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 注意：shardingjdbc中io开头的包与org开头的包会存在冲突，需要看看是什么原因，是版本号么？
 */
@Service
public class OrderDataSourcePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    private final static Logger log = LoggerFactory.getLogger("ShardingSphere-SQL");

    /**
     *
     * @param availableTargetNames 可用的数据源或表名
     * @param preciseShardingValue 要分片的值
     * @return 分片后得到的数据源或表名
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        for (String name : availableTargetNames) {
            Long val = preciseShardingValue.getValue();
            // 对2求模后，最终结果肯定是逻辑库的后缀
            String suffix = "" + (val % 2);
            if (name.endsWith(suffix)) {
                // 返回对应库名
                return name;
            }
        }
        return null;
    }
}
